use entity::user::{admin, auth, custom};
use sea_orm_migration::{prelude::*, sea_orm::Schema};

pub struct Migration;

impl MigrationName for Migration {
    fn name(&self) -> &str {
        "m20220520_123958_users_create"
    }
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        let schema = Schema::new(manager.get_database_backend());

        // basic auth
        let mut table = schema.create_table_from_entity(auth::Entity);
        table.if_not_exists();
        manager.create_table(table).await?;

        // admin
        let mut table = schema.create_table_from_entity(admin::Entity);
        table.if_not_exists().foreign_key(
            ForeignKey::create()
                .from_col(admin::Column::AuthId)
                .to(auth::Entity, auth::Column::Id)
                .on_delete(ForeignKeyAction::Cascade)
                .on_update(ForeignKeyAction::Cascade),
        );

        manager.create_table(table).await?;

        // custom

        let mut table = schema.create_table_from_entity(custom::Entity);
        table.if_not_exists().foreign_key(
            ForeignKey::create()
                .from_col(custom::Column::AuthId)
                .to(auth::Entity, auth::Column::Id)
                .on_delete(ForeignKeyAction::Cascade)
                .on_update(ForeignKeyAction::Cascade),
        );
        manager.create_table(table).await?;

        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(custom::Entity).to_owned())
            .await?;
        manager
            .drop_table(Table::drop().table(admin::Entity).to_owned())
            .await?;
        manager
            .drop_table(Table::drop().table(auth::Entity).to_owned())
            .await?;

        Ok(())
    }
}
